<?php
class Poll_PollController extends Core_Controller_Action_Standard {
    public function addAction() {
        $this->view->status = false; 
        if ($this->getRequest()->isGet()) return $this->_helper->viewRenderer->setNorender(true);
        $viewer   = Engine_Api::_()->user()->getViewer();
        if (!$viewer->getIdentity()) return $this->_helper->viewRenderer->setNorender(true);
        $question = $this->_getParam('question');
        if (!isset($question) || empty($question)) return false;
        $options  = Zend_Json::decode($this->_getParam('options', '[]'));
        $allow_add_option = $this->_getParam('allow_add_option');
        $privacy = $this->_getParam('privacy', 'public');   
                
        $table = Engine_Api::_()->getDbTable('Polls', 'Poll');
        $db    = $table->getAdapter();
        $db->beginTransaction();
        try {
            $poll  = $table->createRow();
            $poll->setFromArray(array(
                'user_id' => $viewer->getIdentity(),
                'title'   => $question,
                'creation_date' => date('Y-m-d H:i:s'),
                'allow_add_option' => ($allow_add_option == false ? 0 : 1),
                'privacy' => $privacy
            ));                                       
            $poll->save();
            
            foreach ($options as $option) {
                Engine_Api::_()->getDbTable('Options', 'Poll')->insert(array(
                    'poll_id' => $poll->getIdentity(),
                    'poll_option' => $option,
                    'votes' => 0
                ));
            }
            
            $action = Engine_Api::_()->getDbTable('actions', 'activity')->addActivity($viewer, $poll, 'poll_create');
            if ($action) {                
                Engine_Api::_()->getDbtable('actions', 'activity')->attachActivity($action, $poll);
                $streamTb = Engine_Api::_()->getDbTable('Stream', 'Activity');
                switch ($privacy) {
                    case 'public':
                    $streamTb->insert(array(
                        'target_type'  => 'everyone',
                        'target_id'    => 0,
                        'subject_type' => 'user',
                        'subject_id'   => $viewer->getIdentity(),
                        'object_type'  => $poll->getType(),
                        'object_id'    => $poll->getIdentity(),
                        'type'         => 'poll_create',
                        'action_id'    => $action->getIdentity()
                    ));
                    $streamTb->insert(array(
                        'target_type'  => 'members',
                        'target_id'    => $viewer->getIdentity(),
                        'subject_type' => 'user',
                        'subject_id'   => $viewer->getIdentity(),
                        'object_type'  => $poll->getType(),
                        'object_id'    => $poll->getIdentity(),
                        'type'         => 'poll_create',
                        'action_id'    => $action->getIdentity()
                    ));
                    break;
                    
                    case 'friends':
                    $streamTb->insert(array(
                        'target_type'  => 'members',
                        'target_id'    => $viewer->getIdentity(),
                        'subject_type' => 'user',
                        'subject_id'   => $viewer->getIdentity(),
                        'object_type'  => $poll->getType(),
                        'object_id'    => $poll->getIdentity(),
                        'type'         => 'poll_create',
                        'action_id'    => $action->getIdentity()
                    ));
                    break;
                    
                    default:
                    break;
                }    
            }
            $this->view->status = true;
            $db->commit();              
        } catch (Exception $e) {            
            $db->rollBack();                
            $this->view->status = false;                  
        }  
    }
    
    public function voteAction() {
        $this->view->status = false;       
        
        if ($this->getRequest()->isPost()) {
            $viewer = Engine_Api::_()->user()->getViewer();
            if ($viewer->getIdentity()) {
                $poll = $this->_getParam('poll');
                $opt  = (int) $this->_getParam('option');
                $show_all = $this->_getParam('show_all', 0); 
                if ($poll && $opt) {
                    $question = Engine_Api::_()->getDbTable('Polls', 'Poll')->find($poll)->current();
                    if ($question) {
                        $actionOwner = Engine_Api::_()->getItem('user', $question->user_id);
                        $option = Engine_Api::_()->getDbTable('Options', 'Poll')->fetchRow("poll_option_id = '$opt'");
                        if ($option) {
                            $vote = Engine_Api::_()->getDbTable('Votes', 'Poll')->fetchRow("user_id = '{$viewer->getIdentity()}' AND option_id = {$option->getIdentity()}");
                            if (!$vote) {
                                $now = date('Y-m-d H:i:s');
                                Engine_Api::_()->getDbTable('Votes', 'Poll')->insert(array(
                                    'user_id' => $viewer->getIdentity(),
                                    'option_id' => $option->getIdentity(),
                                    'creation_date' => $now,
                                    'modified_date' => $now   
                                ));
                                $option->votes++;                                
                                $question->total_votes++;
                                $type = 'vote'; 
                                /// add notification
                                
                                $notifyApi = Engine_Api::_()->getDbtable('notifications', 'activity');
                                $notifyApi->addNotification($actionOwner, $viewer, $question, 'poll_vote',array(
                                            //'amount' => $amount,
                                            //'level' =>  $currentLevel
                                        ));                               
                            } else {
                                $vote->delete();
                                $option->votes--;                                
                                $question->total_votes--;
                                $type = NULL;    
                                // add notification
                                
                                $notifyApi = Engine_Api::_()->getDbtable('notifications', 'activity');
                                $notifyApi->addNotification($actionOwner, $viewer, $question, 'poll_unvote',array(
                                            //'amount' => $amount,
                                            //'level' =>  $currentLevel
                                        )); 
                           }
							$option->save();
                            $question->save();
                            $question->broadcast($type, array('viewer' => $viewer, 'answer' => $option->getTitle()));
                            $this->view->status = true;
                            if ($show_all) $this->view->body = $this->view->partial('_full_details_poll.tpl', 'poll', array('question' => $question, 'options' => $question->getOptions(array('get-all' => $show_all)), 'isAjax' => true));
                            else $this->view->body = $this->view->partial('_displayPoll.tpl', 'poll', array('item' => $question, 'options' => $question->getOptions(), 'noInfo' => $this->_getParam('noInfo')));
                        
                    }
                }
            }
        }
    }
    }
    
    public function showAllOptionsAction() {
        $this->view->status  = false;
        $this->view->context = $context = $this->_helper->contextSwitch->getCurrentContext(); 
        $isAjax = $this->_getParam('isAjax', false);
        $question = Engine_Api::_()->getDbTable('Polls', 'Poll')->find($this->_getParam('poll'))->current();
        if (!$question) return false;
        if ($isAjax) {
            $this->view->body = $this->view->partial('_full_details_poll.tpl', 'poll', array('question' => $question, 'options' => $question->getOptions(array('get-all' => true)), 'isAjax' => true));    
        } else {            
            $this->view->viewer = Engine_Api::_()->user()->getViewer();
            $this->view->question = $question;
            $this->view->options  = $question->getOptions(array('get-all' => true));     
        }
        $this->view->status = true;
    }
    
    public function editAction() {
        $this->view->status = false;
        $token = $this->_getParam('token');
        $question = Engine_Api::_()->getDbTable('Polls', 'Poll')->find(base64_decode($token))->current(); 
        if ($question) {
            $viewer = Engine_Api::_()->user()->getViewer();
            if ($viewer->getIdentity() == $question->user_id) {                
                $this->view->status = true;
                $this->view->body   = $this->view->partial('poll/edit.tpl', 'poll', array('question' => $question, 'options' => $question->getOptions(array('get-all' => true))));    
            }
        }
    }
    
    public function deleteOptionAction() {
        $this->view->status = false;
        $question = Engine_Api::_()->getDbTable('Polls', 'Poll')->find($this->_getParam('poll'))->current(); 
        $viewer   = Engine_Api::_()->user()->getViewer();
        if ($question && $question->user_id == $viewer->getIdentity()) {
            $optTb = Engine_Api::_()->getDbTable('Options', 'Poll');
            $sl    = $optTb->select()->where('poll_id = ?', $question->getIdentity())
                ->where('poll_option_id = ?', $this->_getParam('option')); 
            $option = $optTb->fetchRow($sl);   
            if ($option) {
                $voteTb = Engine_Api::_()->getDbTable('Votes', 'Poll');
                $db     = $voteTb->getAdapter();
                $db->beginTransaction();
                try {
                    $votes = $voteTb->fetchAll("option_id = {$option->getIdentity()}");    
                    foreach ($votes as $vote) {
                        $vote->delete();
                    }          
                    $question->total_votes -= $option->votes;
                    $question->save();
                    $option->delete();
                    $this->view->status = true;
                    $db->commit();
                } catch (Exception $e) {
                    $db->rollBack();
                    $this->view->body = $e->getMessage();                    
                }  
            }
        }
    }
    
    public function deleteAction() {
        $this->view->status = false;
        $token = $this->_getParam('token');
        $question = Engine_Api::_()->getDbTable('Polls', 'Poll')->find(base64_decode($token))->current(); 
        $viewer = Engine_Api::_()->user()->getViewer();
        if ($question && $question->user_id == $viewer->getIdentity()) {
            $voteTb = Engine_Api::_()->getDbTable('Votes', 'Poll'); 
            $options = Engine_Api::_()->getDbTable('Options', 'Poll')->fetchAll("poll_id = {$question->getIdentity()}");       
            $db     = Engine_Db_Table::getDefaultAdapter();
            $db->beginTransaction();
            try {
                foreach ($options as $option) {
                    Engine_Api::_()->getDbTable('Votes', 'Poll')->delete("option_id = {$option->getIdentity()}");
                    $option->delete();    
                }
                
                $attachments = Engine_Api::_()->getDbTable('Attachments', 'Activity')->fetchAll("type = '{$question->getType()}' AND id = {$question->getIdentity()}");
                if ($attachments) {
                    foreach ($attachments as $attachment) {
                        $action = Engine_Api::_()->getDbTable('Actions', 'Activity')->fetchRow("action_id = {$attachment->action_id}");
                        $action->deleteItem();
                        $attachment->delete();
                    }
                }
                
                $question->delete();
                $this->view->status = true;
                $db->commit();
            } catch (Exception $e) {
                $db->rollBack();
            }
        }    
    }
    
    public function addOptionAction() {
        $this->view->status = false;
        $viewer   = Engine_Api::_()->user()->getViewer();
        if (!$viewer->getIdentity()) return false;
        $question = Engine_Api::_()->getDbTable('Polls', 'Poll')->find($this->_getParam('poll'))->current();
        $option   = $this->_getParam('option');
        $full     = $this->_getParam('full', 0);
        if ($question && ($question->allow_add_option == 1 || $question->user_id == $viewer->getIdentity()) && $option) {
            $tb  = Engine_Api::_()->getDbTable('Options', 'Poll');
            $row = $tb->fetchRow("poll_id = {$question->getIdentity()} AND poll_option = '$option'"); 
            if (!$row) {
                Engine_Api::_()->getDbTable('Options', 'Poll')->insert(array(
                    'poll_id' => $question->getIdentity(),
                    'poll_option' => $option,
                    'votes' => 0
                ));
                $this->view->status = true;
                if ($full == 1) $this->view->body = $this->view->partial('_full_details_poll.tpl', 'poll', array('question' => $question, 'options' => $question->getOptions(array('get-all' => true)), 'isAjax' => true));
                else $this->view->body = $this->view->partial('_displayPoll.tpl', 'poll', array('item' => $question, 'options' => $question->getOptions(), 'noInfo' => $this->_getParam('noInfo', false)));    
            } else {
                $this->view->status = false;    
                $this->view->msg = "Option <strong><u>$option</u></strong> has been existed.";
            }           
        }
    }
    
    public function votersAction() {
        $this->view->viewer = $viewer   = Engine_Api::_()->user()->getViewer();
        if (!$viewer->getIdentity()) return false;
        $this->view->isAjax = $isAjax = $this->_getParam('isAjax', 0);
        if ($isAjax) $this->_helper->layout()->disableLayout(true);
        $this->view->option = $option = Engine_Api::_()->getDbTable('Options', 'Poll')->find($this->_getParam('option'))->current();    
        if ($option) {
            $tb = Engine_Api::_()->getDbTable('Votes', 'Poll');
            $sl = $tb->select()->where('option_id = ?', $option->getIdentity());
            $this->view->paginator = $paginator = Zend_Paginator::factory($sl);
            $paginator->setItemCountPerPage(6);
            $paginator->setCurrentPageNumber($this->_getParam('page', 1));
        }
    }
    
    public function askFriendsAction() {
        $this->view->status = false;
        $this->view->viewer = $viewer   = Engine_Api::_()->user()->getViewer();
        if (!$viewer->getIdentity()) return false;
        $this->view->question = $question = Engine_Api::_()->getDbTable('Polls', 'Poll')->find($this->_getParam('poll'))->current();
        if ($question) {
            if ($this->getRequest()->isPost()) {
                $this->_helper->layout()->disableLayout(true);
                $fids = $this->_getParam('friends');
                $userApi = Engine_Api::_()->user();
                $notifTb = Engine_Api::_()->getDbTable('Notifications', 'Activity');
                $db      = $notifTb->getAdapter();
                $db->beginTransaction();
                try {
                    foreach ($fids as $f) {
                        $u = $userApi->getUser($f);
                        $notifTb->addNotification($u, $viewer, $question, 'poll_ask');
                    }    
                    $db->commit();
                
                    return $this->_forward('success', 'utility', 'core', array(
                        'smoothboxClose' => true,
                        'parentRefresh' => false,
                        'messages' => array('Sending question done.')
                    ));
                } catch (Exception $e) {$db->rollBack();}
            }
            $this->view->friends = Engine_Api::_()->poll()->getFriends($viewer);
            $this->view->status  = true;        
        }    
    }
    
    public function followAction() {
        $this->view->status = false;
        $question = Engine_Api::_()->getDbTable('Polls', 'Poll')->find($this->_getParam('poll'))->current();
        $viewer   = Engine_Api::_()->user()->getViewer();
        if (!$question || !$viewer->getIdentity() || ($question->user_id == $viewer->getIdentity())) return false; 
        $tb = Engine_Api::_()->getDbTable('Follow', 'Poll'); 
        $db = $tb->getAdapter();
        $db->beginTransaction();
        try {            
            $r  = $question->isFollowed($viewer, true);
            if ($r) {
                $r->delete();
                $this->view->title = $this->view->translate('Follow');            
            } else {
                $tb->insert(array(
                    'user_id' => $viewer->getIdentity(),
                    'question_id' => $question->getIdentity()
                ));
                $this->view->title = $this->view->translate('Unfollow');
            }
            $db->commit();
            $this->view->status = true;
        } catch (Exception $e) {$db->rollBack();}    
    }
    
    public function browseAction() {
        
        $actionTypes = Engine_Api::_()->getDbtable('actionTypes', 'activity')->getActionType('poll_create');

        if($actionTypes && $actionTypes->commentable == 0){
            $actionTypes->commentable = 1;  
        }    
        $actionTypes->save();   
                
        $this->_helper->content
        ->setNoRender()
        ->setEnabled()
        ;    
    }
    
    public function manageAction() {
        if( !$this->_helper->requireUser()->isValid() ) return; 
        $viewer   = Engine_Api::_()->user()->getViewer(); 
        $params['user_id'] = $viewer->getIdentity();        
        $this->view->paginator = $paginator = Engine_Api::_()->poll()->pollPaginator($params);
        $paginator->setItemCountPerPage(15);
        $paginator->setCurrentPageNumber($this->_getParam('page', 1));
        
        $this->view->do = $do = $this->_getParam('do');
        
        if ($do == 'create') {
            $this->view->navigation = $navigation = Engine_Api::_()->getApi('menus', 'core')
            ->getNavigation('poll_main', array (), 'poll_main_ask');
        } else {
            $this->view->navigation = $navigation = Engine_Api::_()->getApi('menus', 'core')
            ->getNavigation('poll_main', array (), 'poll_main_manage');
        }
    } 
}
